package com.sojson.config.datasource.dynamic.datasource;

import javax.sql.DataSource;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;

/**
 * 自定义Dynamic获取数据源逻辑(用来缓存数据源)
 * 
 * @author liu
 * @date 2022-01-11
 */
public class CustomDynamicRoutingDataSource extends DynamicRoutingDataSource {

    /** 数据源 */
    public static final ThreadLocal<DataSource> DATA_SOURCE = new ThreadLocal<>();

    /**
     * 取得当前使用哪个数据源
     *
     * @return
     */
    @Override
    public DataSource determineDataSource() {
        DataSource dataSource = DATA_SOURCE.get();
        if (dataSource != null) {
            return dataSource;
        }

        dataSource = getDataSource(DynamicDataSourceContextHolder.peek());
        DATA_SOURCE.set(dataSource);
        return dataSource;
    }

}